package com.leaves.contoller;

import com.leaves.common.util.excel.ExcelUtils;
import com.leaves.entity.UserInfo;
import com.leaves.entity.excel.UserInfoExcel;
import com.leaves.exception.MessageCenterException;
import com.leaves.response.ApiResult;
import com.leaves.service.UserInfoService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2022年08月29日  16时55分09秒
 * @Description:
 */
@RestController
@RequestMapping("/v1")
public class ExcelController {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private MapperFacade mapperFacade;

    @PostMapping("/import/user/excel")
    public ApiResult importUser(@RequestParam("file") MultipartFile file) {
        try {
            List<UserInfoExcel> list = ExcelUtils.readMultipartFile(file, UserInfoExcel.class);
            list.forEach(x -> {
                System.out.println("x = " + x);
            });
            return ApiResult.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new MessageCenterException("文件导入失败");
        }
    }

    /**
     * 按对象导出
     *
     * @param response
     */
    @GetMapping("/export/user/excel")
    public void exportUser(HttpServletResponse response) {
        List<UserInfo> userInfoList = userInfoService.list();
        List<UserInfoExcel> userInfoExcelList = mapperFacade.mapAsList(userInfoList, UserInfoExcel.class);
        userInfoExcelList.forEach(x -> {
            System.out.println("x = " + x);
        });
        ExcelUtils.export(response, "账号信息表", userInfoExcelList, UserInfoExcel.class);
    }

    @GetMapping("/export/user/excelTemplate")
    public void exportUserTemplate(HttpServletResponse response) {
        //模板数据
//        ExcelUtils.exportTemplate(response, "账号信息模板表", UserInfoExcel.class);
        //带例子的模板数据
        ExcelUtils.exportTemplate(response, "账号信息模板表", UserInfoExcel.class, true);
    }
}
